#!/usr/bin/env node

/**
 * 测试修复后的代币创建 - 验证供应量问题
 */

const axios = require('axios');

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:7172';

// 测试数据 - 使用较小的供应量便于验证
const testData = {
  name: 'Fixed Supply Test Token',
  symbol: 'FSTT',
  decimals: 9,
  supply: '1000000000000000', // 1,000,000 个代币 * 10^9 (9个小数位)
  description: '测试修复后的代币供应量',
  creator: 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac',
  enablePrettyAddress: false,
  revokeUpdateAuthority: false,
  revokeFreezeAuthority: false,
  revokeMintAuthority: false,
};

async function testFixedTokenCreation() {
  console.log('🧪 测试修复后的代币创建');
  console.log('='.repeat(50));
  
  try {
    // 1. 检查后端服务
    console.log('\n1️⃣ 检查后端服务...');
    await axios.get(`${API_URL}/api/health`);
    console.log('✅ 后端服务正常');
    
    // 2. 创建代币
    console.log('\n2️⃣ 创建测试代币...');
    console.log('📝 发送数据:', JSON.stringify({
      ...testData,
      supply: `${testData.supply} (${Number(testData.supply) / Math.pow(10, 9)} 个代币)`
    }, null, 2));
    
    const createResponse = await axios.post(`${API_URL}/api/tokens`, testData);
    
    if (createResponse.data.success) {
      const responseData = createResponse.data.data || createResponse.data;
      const newToken = responseData.token || responseData;
      console.log('\n✅ 代币创建成功!');
      console.log('📋 代币信息:', JSON.stringify(newToken, null, 2));
      
      const mintAddress = newToken.mint;
      if (!mintAddress) {
        console.log('❌ 无法找到mint地址');
        return;
      }
      
      console.log(`\n🪙 新代币地址: ${mintAddress}`);
      
      // 3. 等待几秒后查询链上状态
      console.log('\n3️⃣ 等待5秒后查询链上状态...');
      await new Promise(resolve => setTimeout(resolve, 5000));
      
      // 4. 使用我们的代币信息查询脚本
      console.log('\n4️⃣ 查询链上供应量...');
      
      const { Connection, PublicKey } = require('@solana/web3.js');
      const connection = new Connection('https://api.devnet.solana.com', 'confirmed');
      
      try {
        const mintInfo = await connection.getParsedAccountInfo(new PublicKey(mintAddress));
        if (mintInfo.value && mintInfo.value.data.parsed) {
          const { decimals, supply } = mintInfo.value.data.parsed.info;
          const actualSupply = Number(supply) / Math.pow(10, decimals);
          
          console.log(`📊 链上供应量信息:`);
          console.log(`- 原始供应量: ${supply}`);
          console.log(`- 小数位数: ${decimals}`);
          console.log(`- 格式化供应量: ${actualSupply.toLocaleString()} 个代币`);
          
          // 5. 验证结果
          const expectedSupply = Number(testData.supply) / Math.pow(10, testData.decimals);
          console.log(`\n5️⃣ 验证结果:`);
          console.log(`- 期望供应量: ${expectedSupply.toLocaleString()} 个代币`);
          console.log(`- 实际供应量: ${actualSupply.toLocaleString()} 个代币`);
          
          if (Math.abs(actualSupply - expectedSupply) < 0.001) {
            console.log('✅ 供应量验证成功！修复生效！');
          } else {
            console.log('❌ 供应量不匹配，可能还有问题');
          }
          
        } else {
          console.log('❌ 无法获取链上mint信息');
        }
      } catch (error) {
        console.log('❌ 查询链上信息失败:', error.message);
      }
      
      // 6. 生成测试报告
      console.log('\n6️⃣ 测试报告:');
      console.log(`🔗 Solscan: https://solscan.io/token/${mintAddress}?cluster=devnet`);
      console.log(`🔗 Explorer: https://explorer.solana.com/address/${mintAddress}?cluster=devnet`);
      
    } else {
      console.log('❌ 代币创建失败:', createResponse.data.message);
    }
    
  } catch (error) {
    console.log('❌ 测试失败:', error.response?.data?.message || error.message);
    if (error.response?.data) {
      console.log('错误详情:', JSON.stringify(error.response.data, null, 2));
    }
  }
}

// 运行测试
testFixedTokenCreation();
